package de.uni.muenster.idw2.location.bluetooth.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;


/**
 * This class is only for debugging purposes and the functionality is related with the 
 * generation of "fake" measurements stored in files so that is not necessary to have 
 * installed dongles (not even bluetooth device in the phone) to test the program.
 * @author lrodriguez
 *
 */
public class MeasurementsThread extends Thread {
    
	List<Measurement> measurements;
	IFakeReceiver receiver;
	MeasurementFileReader reader;
	String directory;
	
	public MeasurementsThread(IFakeReceiver receiver, String directory){
		this.receiver = receiver;
		reader = new MeasurementFileReader();
		this.directory = directory;
	}
	
    @Override
    public void run(){
		List <Measurement> readMeasurements = reader.readMeasurements(directory);
		long time = 0L;
		int i = 0;
		long total = 2000L;//5000L; //ten seconds discovering.
		long lapse = 200L;  //one second between discoveries.
		boolean cyclic = true;
		
		while(true){
			try {
		        long secs = 0L;	
		        boolean nextRound = true; 
		        if (cyclic && i >= readMeasurements.size() ) {
		        	i = 0; 
		        }
		        
				for(;i < readMeasurements.size(); i++) {
					Measurement m = readMeasurements.get(i);
					if (nextRound){
					  time = m.fileTime;
					  nextRound = false;
					}
					if (time == m.fileTime){
					   receiver.OnReceive(BluetoothDevice.ACTION_FOUND, null, null, m.RSSI, m.address);
					   sleep(lapse);
					   secs +=lapse; 
					}
					else {break;}
				}
				receiver.OnReceive(BluetoothAdapter.ACTION_DISCOVERY_FINISHED, null, null, Short.MIN_VALUE, "");
				if (secs < total)
				  sleep(total - secs);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
    
    public interface IFakeReceiver{
    	void OnReceive(String action, Context context, Intent intent, short RSSI, String address); 
    }
        
	public class Measurement {
    	String fileName;
    	long fileTime;
    	short RSSI;
    	String address;
    	
    	public Measurement(String fileName, long fileTime, short RSSI, String address){
    	   this.fileName  = fileName;
    	   this.fileTime = fileTime;
    	   this.RSSI = RSSI; 
    	   this.address = address;
    	}
    }
	
    class MeasurementFileReader{
	  public List<Measurement> readMeasurements(String directory){
		  List<Measurement> result = new ArrayList<Measurement>();
		  //todo: read the list of measurements
		  //return them in the order of the name value converted to long;
		 File f  = new File(directory);
		 //the condition have true because  isDirectory fails.
		 if (f.isDirectory() || true) {
		   File [] files = f.listFiles();
		   if (files!= null) {
			   for (int i = 0; i < files.length; i ++){
				   File currentFile = files [i];
				   String fileName = currentFile.getName();
			    	  //check that;
				   if (!getFileExt(fileName).equalsIgnoreCase(".csv"))
					    continue;
			       long fileTime = 0L;
			       try {
			    	   fileTime = Long.parseLong(extractExt(fileName));
			       }
			       catch (NumberFormatException ne){
			    	   fileTime = 0L;
			       }
				   
				   try {
					 BufferedReader br = new BufferedReader(new FileReader(currentFile));
					 String line; 
					 do  {
				       line = br.readLine();
				       if (line!= null) {
				    	  String [] fields = line.trim().split("\t");
				    	  String address = fields[0];
				    	  short RSSI = Short.parseShort(fields[1]);
				    	  result.add(new Measurement(fileName, fileTime, RSSI, address));
				       }
					 }
					 while(line!= null);
				   } 
				   catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				   } catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				   }
			   }  
		    }
		 }
		 
		 Collections.sort(result, new Comparator<Measurement>(){
			 public int compare(Measurement arg0, Measurement arg1){
				 int result = 0;
				 if (arg0.fileTime > arg1.fileTime){
					 result = 1; 
				 }
				 if (arg0.fileTime < arg1.fileTime){
					 result = -1; 
				 }
				 if (arg0.fileTime == arg1.fileTime){
					 result = 0; 
				 }
				 return result;
			 }
		 } );
		 return result;
	  }
	 
	  public String extractExt(String filename){
		 int index = filename.lastIndexOf(".");
		 if (index != -1) {
		   return filename.substring(0, index); 
		 }
		 else return ""; 
	  }
	  
	  public String getFileExt(String filename){
		 int index = filename.lastIndexOf(".");
		 if (index != -1) {
		    return filename.substring(index); 
		 }
		 else return ""; 
	  }
   }
  
}
